package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.HistorySearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 陈辉
 * @data 2024 10:36
 */
@Service
public class HistorySearchServiceImpl implements HistorySearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存搜索记录
     *
     * @param searchWords
     * @param userId
     */
    @Async
    public void saveHistory(String searchWords, Integer userId) {
        //区分当前用户是否是游客
        // 如果id无效，或者是0(游客)：流程结束
        if (userId == null || userId == 0)
            return ;

        //1. 先查询当前用户对本次搜索词之前有没有搜过
        ApUserSearch historySearch = mongoTemplate.findOne(Query.query(Criteria
                .where("userId")
                .is(userId)
                .and("keyword").is(searchWords)), ApUserSearch.class);

        //2. 有：将该记录的时间更新为当前时间即可
        if (historySearch != null) {
            historySearch.setCreatedTime(new Date());
            mongoTemplate.save(historySearch);   //更新
        } else {
            //3. 没有：判断当前用户搜索记录总量是否超过10
            List<ApUserSearch> list = mongoTemplate.find(
                    Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.ASC, "createdTime")),
                    ApUserSearch.class);

            if (list != null && list.size() >= 10) {
                //5. 超过10：将最旧的记录删除，并保存本次记录
                mongoTemplate.remove(list.get(0));
            }

            //4. 没有超过：直接保存本次记录即可
            ApUserSearch search = new ApUserSearch();
            search.setKeyword(searchWords);
            search.setUserId(userId);
            search.setCreatedTime(new Date());
            mongoTemplate.save(search);     //新增
        }
    }

    /**
     * 加载用户搜索记录
     *
     * @return
     */
    @Override
    public ResponseResult load() {
        //1. 拿到当前用户id
        Integer userId = ApThreadLocalUtil.get();
        //2. 区分当前用户是否是游客
        //2.1 如果id无效，或者是0(游客)：流程结束
        if (userId == null || userId == 0)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        //2.2 正常用户：则查询mongo加载对应的历史记录返回
        List<ApUserSearch> list = mongoTemplate.find(Query
                        .query(Criteria.where("userId").is(userId))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime")),
                ApUserSearch.class);

        return ResponseResult.okResult(list);
    }

    /**
     * 删除用户搜索记录
     *
     * @param search
     * @return
     */
    @Override
    public ResponseResult del(ApUserSearch search) {
        //1. 参数校验
        if (search == null || StringUtils.isEmpty(search.getId()))
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);

        //2. 删除mongo中对应的搜索记录
        mongoTemplate.remove(search);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
